﻿using CommandLine;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Quickly.Identity.Migrations;
using Serilog;
using System.Text.Json;

namespace Quickly.Identity.EntityFrameworkCore
{
    public class MigrateQuickIdentityDbContextFactory : IDesignTimeDbContextFactory<MigrateQuickIdentityDbContext>
    {
        /// <summary>
        /// 接收命令行传递的参数
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public MigrateQuickIdentityDbContext CreateDbContext(string[] args)
        {
            var loggerFactory = LoggerFactory.Create(builder => builder.ClearProviders()
                                                                                   .AddConsole()
                                                                                   .AddSerilog()
                                                                                   .SetMinimumLevel(LogLevel.Debug));

            var logger = loggerFactory.CreateLogger<MigrateQuickIdentityDbContextFactory>();
            logger.LogDebug("Command-line args:{@args}", JsonSerializer.Serialize(args));

            MigrationOptions? migrationOptions = null;

            Parser.Default.ParseArguments<MigrationOptions>(args)
                .WithParsed(value => migrationOptions = value)
                .WithNotParsed(errors => logger.LogError("@{errors}", errors));

            var options = new DbContextOptionsBuilder();

            options.UseLoggerFactory(loggerFactory);

            QuickIdentityEntityFrameworkCoreExtensions.ValidateDatabaseConnectionString(
                migrationOptions?.Database,
                migrationOptions?.ConnectionString);

            QuickIdentityEntityFrameworkCoreExtensions.ConfigureDbContextOptions(
                migrationOptions!.Database!, 
                migrationOptions!.ConnectionString!,
                options);

            return new MigrateQuickIdentityDbContext(options.Options);
        }
    }
}
